import cfg
import job

import os

def jobs_with_tag(tag,verify=False):
	p = os.path.join(cfg.tag_root_dir,tag)
	if os.path.exists(p):
		jobs=set(os.listdir(p))
	else:
		jobs=set()
	if verify:
		date = cfg.sysdate()
		for j in jobs:
			if tag not in job.Job(j,date,fake=True).tags:
				try:
					os.remove(os.path.join(p,j))
				except:
					pass
		return jobs_with_tag(tag,verify=False)
	return jobs

def jobs_with_tags(tags,verify=False):
	if len(tags)==0:
		return set()
	else:
		tags=set(tags)
	jobs = jobs_with_tag(tags.pop(),verify)
	for tag in tags:
		jobs &= jobs_with_tag(tag,verify)
	return jobs

def jobs_by_tag(verify=False):
	out = {}
	for tag in os.listdir(cfg.tag_root_dir):
		tag_dir = os.path.join(cfg.tag_root_dir,tag)
		if verify:
			for job in os.listdir(tag_dir):
				job_path = os.path.join(cfg.job_root_dir,job+'.ini')
				if not os.path.exists(job_path):
					os.remove(os.path.join(tag_dir,job))
		out[tag] = os.listdir(tag_dir)
	return out 

def job_tags(job_name):
	return job.Job(job_name,cfg.sysdate(),fake=True).tags

def reload():
	date = cfg.sysdate()
	for j in job.all_job_names():
		for tag in job.Job(j,date,fake=True).tags:
			p = os.path.join(cfg.tag_root_dir,tag)
			if not os.path.exists(p):
				os.makedirs(p)
			t = os.path.join(p,j)
			if not os.path.exists(t):
				open(t,"w")

def get_hint(t):
	return cfg.get('tag','hint',t,'')

if __name__=="__main__":
	#date = cfg.sysdate()
	#print dict([(j,job.Job(j,date,fake=True).tags) for j in job.all_job_names()])
	reload()
	print jobs_with_tags(["aaa"],True)
